package com.achang.achangmall.product.service.impl;

import com.achang.achangmall.product.vo.Catelog2Vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.achang.common.utils.PageUtils;
import com.achang.common.utils.Query;

import com.achang.achangmall.product.dao.CategoryDao;
import com.achang.achangmall.product.entity.CategoryEntity;
import com.achang.achangmall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //查出所有分类以及子分类，以树形结构组装
    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> allList = baseMapper.selectList(null);

        List<CategoryEntity> parentList = allList.stream()
                .filter(item -> item.getParentCid() == 0)
                .map(item -> {
                    item.setChildren(getChildren(item, allList));
                    return item;
                }).sorted((item1, item2) -> {
                    return item1.getSort() - item2.getSort();
                })
                .collect(Collectors.toList());
        return parentList;
    }

    @Override
    public void removeCategory(Long[] catIds) {
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    //找到catelogId的完整路径:[父/子/孙]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> list = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, list);

        Collections.reverse(parentPath);
        return (Long[]) list.toArray(new Long[parentPath.size()]);
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        //查询一级分类
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
    }

    @Override
    public Map<Long, List<Catelog2Vo>> getCatelogJson() {
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) {
            //缓存中没有
            Map<Long, List<Catelog2Vo>> catelogJsonFromDB = getCatelogJsonFromDBWithSpringCache();
            return catelogJsonFromDB;
        }

        //因为转化的对象是复杂对象，所以通过TypeReference
        Map<Long, List<Catelog2Vo>> catelogJsonFromDB = JSON.parseObject(catelogJson, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
        });
        return catelogJsonFromDB;
    }


    //SpringCache缓存
    @Cacheable(key = "#root.methodName",value = {"catagory"},sync = true)
    public Map<Long, List<Catelog2Vo>> getCatelogJsonFromDBWithSpringCache() {
        RLock lock = redissonClient.getLock("catelog-lock");
        lock.lock();
        //抢锁成功。。。执行业务
        Map<Long, List<Catelog2Vo>> resultMap = null;
        try {
            Thread.sleep(30000);
            resultMap = getLongListMap();
        } finally {
            lock.unlock();
            return resultMap;
        }
    }

    //Redisson分布式锁
    public Map<Long, List<Catelog2Vo>> getCatelogJsonFromDBWithRedissonLock() {
        RLock lock = redissonClient.getLock("catelog-lock");
        lock.lock();
        //抢锁成功。。。执行业务
        Map<Long, List<Catelog2Vo>> resultMap = null;
        try {
            Thread.sleep(30000);
            resultMap = getLongListMap();
        } finally {
            lock.unlock();
            return resultMap;
        }
    }

    //从数据库查询数据【Redis分布式锁】
    public Map<Long, List<Catelog2Vo>> getCatelogJsonFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //设置redis分布式锁，30s自动删除锁
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300L, TimeUnit.SECONDS);
        if (isLock) {
            //抢锁成功。。。执行业务
            Map<Long, List<Catelog2Vo>> resultMap = null;
            try {
                resultMap = getLongListMap();
            } finally {
                //lua脚本解锁：让获取数据+对比数据成为原子操作
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long lock = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"),
                        uuid);
            }
            return resultMap;

        } else {
            //抢锁失败。。。重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromDBWithRedisLock();
        }
    }

    //从缓存中获取数据的业务代码
    private Map<Long, List<Catelog2Vo>> getLongListMap() {
        //判断缓存是否已经有数据，防止之前的线程已经放好数据
        String catelogJson = redisTemplate.opsForValue().get("catelogJsonFromDB");
        if (!StringUtils.isEmpty(catelogJson)) {
            //因为转化的对象是复杂对象，所以通过TypeReference
            Map<Long, List<Catelog2Vo>> resultMap = JSON.parseObject(catelogJson, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
            });
            return resultMap;
        }

        //将数据库的多次交互，转为一次，一次性查询所有数据
        List<CategoryEntity> allList = baseMapper.selectList(null);
        //查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(allList, 0L);
        //分装数据
        Map<Long, List<Catelog2Vo>> resultMap = level1Categorys.stream().collect(Collectors.toMap(CategoryEntity::getCatId, v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> list = getParent_cid(allList, v.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (!StringUtils.isEmpty(list)) {
                catelog2VoList = list.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //封装二级分类的三级分类
                    List<CategoryEntity> entityList = getParent_cid(allList, item.getCatId());
                    if (!StringUtils.isEmpty(entityList)) {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = entityList.stream().map(m -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), m.getCatId().toString(), m.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
                return catelog2VoList;
            }
            return catelog2VoList;
        }));

        //放入缓存
        redisTemplate.opsForValue().set("catelogJson", JSON.toJSONString(resultMap), 1L, TimeUnit.DAYS);

        return resultMap;
    }


    //从数据库查询数据【本地锁】
    public Map<Long, List<Catelog2Vo>> getCatelogJsonFromDBWithLocalLock() {
        synchronized (this) {
            //判断缓存是否已经有数据，防止之前的线程已经放好数据
            return getLongListMap();
        }
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> allList, Long parent_cid) {
        List<CategoryEntity> collect = allList.stream().filter(item -> {
            return item.getParentCid().equals(parent_cid);
        }).collect(Collectors.toList());
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId, ArrayList<Long> list) {
        list.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), list);
        }
        return list;
    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> allList) {
        List<CategoryEntity> lastList = allList.stream()
                .filter(item -> {
                    return item.getParentCid().longValue() == root.getCatId().longValue();
                })
                .map(item -> {
                    item.setChildren(getChildren(item, allList));
                    return item;
                })
                .sorted(
                        (item1, item2) -> {
                            return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                        })
                .collect(Collectors.toList());

        return lastList;
    }

}